#include "QLoggerLib.h"
#include <qstring.h>
#include <QMutex>
#include <QDateTime>
#include <QFile>
#include <QTextStream>
#include <QCoreApplication>
#include <QDir>


namespace
{
	QString g_log_directory{"FunctionLog"};
	QMutex g_mutex;
#if (QT_VERSION <= QT_VERSION_CHECK(5,0,0))
	void OutputMessage(QtMsgType type, const char* msg)
	{
		g_mutex.lock();
		QString _outinfo{};
		switch (type)
		{
		case QtDebugMsg:
			_outinfo = QString("Debug: ");
			break;
		case QtWarningMsg:
			_outinfo = QString("Warning: ");
			break;
		case QtCriticalMsg:
			_outinfo = QString("Critical: ");
			break;
		case QtFatalMsg:
			_outinfo = QString("Fatal: ");
			break;
		case QtInfoMsg:
			_outinfo = QString("Info: ");
			break;
		default:
			break;
		}
#else
	void OutputMessage(QtMsgType type, const QMessageLogContext& context, const QString& msg)
	{
		g_mutex.lock();
		QString _outinfo{};
		QString _fileinfo{ QString("File (%1) Line(%2)").arg(context.file).arg(context.line) };
		switch (type)
		{
		case QtDebugMsg:
			_outinfo = QString("Debug: ");
			break;
		case QtWarningMsg:
			_outinfo = QString("Warning: ");
			break;
		case QtCriticalMsg:
			_outinfo = QString("Critical: %1").arg(_fileinfo);
			break;
		case QtFatalMsg:
			_outinfo = QString("Fatal: %1").arg(_fileinfo);
			break;
		case QtInfoMsg:
			_outinfo = QString("Info: %1").arg(_fileinfo);
			break;
		default:
			break;
		}
#endif // (QT_VERSION )
		QString _curDateTime{ QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd") };
		QString _fileDateTime{ QDateTime::currentDateTime().toString("yyyyMMdd") };

		QString message{ QString("%1 :%2 || %3").arg(_curDateTime).arg(_outinfo).arg(msg) };

		QString _dir = QString("%1/%2").arg(QCoreApplication::applicationDirPath(), g_log_directory);
		QDir _tmpdir(_dir);
		if (!_tmpdir.exists())
			_tmpdir.mkdir(_dir);

		QString _logfile{ QString("%1/%2.log").arg(_dir).arg(_fileDateTime) };

		QFile file(_logfile);
		if (file.open(QFile::WriteOnly | QFile::Append))
		{
			QTextStream _stream(&file);
			_stream.setCodec("UTF-8");
			_stream << message << "\r\n";
		}
		file.flush();
		file.close();
		g_mutex.unlock();
	}
}

QLoggerLib::QLoggerLib()
{
}

const void QLoggerLib::Init()const noexcept
{
#if (QT_VERSION <= QT_VERSION_CHECK(5,0,0))
	qInstallMsgHandler(OutputMessage);
#else
	qInstallMessageHandler(OutputMessage);
#endif // (QT_VERSION <= QT_VERSION_CHECK(5,0,0))

	
}

